package com.sunsharing.sysdb;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.sql.DataSource;


public class DbTransaction {

    private DefaultTransactionDefinition transactionDef;
    private DataSourceTransactionManager txManager;
    private TransactionStatus status;

    public DbTransaction(DataSource dataSource) {
        transactionDef = new DefaultTransactionDefinition();
        transactionDef.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        transactionDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        txManager = new DataSourceTransactionManager(dataSource);
    }

    public void start() {
        status = txManager.getTransaction(transactionDef);
    }

    public void commit() {
        txManager.commit(status);
    }

    public void rollback() {
        txManager.rollback(status);
    }

}
